package com.work.demo.threaddemo;

import java.util.concurrent.CompletableFuture;

public class ThreadSyncExample {
    public static void main(String[] args) {
        CompletableFuture<Boolean> verificationFuture = new CompletableFuture<>();
        
        Thread thread1 = new Thread(new WorkerThread(verificationFuture));
        Thread thread2 = new Thread(new CoordinatorThread(verificationFuture));
        
        thread1.start();
        thread2.start();
    }
}

class WorkerThread implements Runnable {
    private final CompletableFuture<Boolean> verificationFuture;
    
    public WorkerThread(CompletableFuture<Boolean> verificationFuture) {
        this.verificationFuture = verificationFuture;
    }
    
    @Override
    public void run() {
        System.out.println("WorkerThread is doing some work.");
        
        // 模拟耗时的任务
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        // 模拟验证结果
        boolean verificationResult = true; // 修改为需要验证的逻辑
        
        if (verificationResult) {
            verificationFuture.complete(true); // 验证成功，通知CoordinatorThread继续执行
        } else {
            verificationFuture.complete(false); // 验证失败，通知CoordinatorThread取消执行
        }
    }
}

class CoordinatorThread implements Runnable {
    private final CompletableFuture<Boolean> verificationFuture;
    
    public CoordinatorThread(CompletableFuture<Boolean> verificationFuture) {
        this.verificationFuture = verificationFuture;
    }
    
    @Override
    public void run() {
        System.out.println("CoordinatorThread is waiting for WorkerThread to finish.");
        
        try {
            Boolean verificationResult = verificationFuture.get();
            
            if (verificationResult) {
                System.out.println("CoordinatorThread received the successful verification and continues its work.");
                
                // 在这里可以继续执行其他操作
            } else {
                System.out.println("CoordinatorThread received the failed verification and cancels its work.");
                
                // 取消线程执行，可以使用return或抛出异常等方式
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
